import os
import subprocess
import shutil


import sys

print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument List:', str(sys.argv))

root = os.getcwd()
if len(sys.argv) >= 2 :
    root=sys.argv[1]



libPaths = []
libPaths.append('/lib/SDL-1.2.15/include/SDL/')
libPaths.append('/lib/SDL-1.2.15/include/')
libPaths.append('/lib/SDL_image-1.2.12/include/')
libPaths.append('/lib/SDL_ttf-2.0.11/include/')

#f = open(root+"/src.txt", 'w')

depFile = open(root+"/dependency.mk", 'w').close #clear
depFile = open(root+"/dependency.mk", 'a')

def listDir( dir, level):
    lst = os.listdir(dir)
    for elt in lst:
        fullPath = dir+'\\'+elt
        fileName, fileExt = os.path.splitext(elt)
        if fileExt == '.cpp':
        #file.write(' '*4*level + elt + '\n');
            cmd = ['gcc', '-E', '-MM', fullPath,'-MF',dir+'\\'+fileName+'.d.mk']
            
            #append libs paths to cmd line
            for lib in libPaths:
                cmd.append('-I'+root+lib);
                
            #exec cmd line
            p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)

            #result...
            result = p.communicate()
            rc = p.returncode
            if rc == 0:
                print("[OK]"+fileName)
            else:
                print("[FAIL]"+fileName)
                
            #add le dernier .d.mk au fichier "dependency.mk"
            lastDepFile = open(dir+'\\'+fileName+'.d.mk')
            shutil.copyfileobj(lastDepFile, depFile)
            lastDepFile.close()
            os.remove(dir+'\\'+fileName+'.d.mk')
            
        if os.path.isdir(fullPath):
            listDir(fullPath, level+1)
            
    return


print('Listing de '+root+'-----------------\n')

listDir(root,0)

print('--------------------------------------')

depFile.close()
print('dependency.mk updated')
